# -*- coding:utf8 -*-
"""
封面新闻内部的API调用
"""
from __future__ import print_function, unicode_literals
import requests
import json
from logger_utility.loggconfig import getLogger


OFFLINE_IP = '192.168.64.17:10089'
ONLINE_IP = ''
logger = getLogger("CoverW2v")


def similar_top10_words(words, ip=OFFLINE_IP):
    """
    获取最接近的10个词语
    :param words:
    :return:
    """
    url = 'http://{}/most_similar_top10/'.format(ip)
    data = {
        'words': words
    }
    r = requests.post(url, data=json.dumps(data))
    dict_ = json.loads(r.text)
    if dict_.get('err_code') != '00':
        logger.warning("Simlar Top10 Error, Code:%s, Msg:%s", dict_.get('err_code'), dict_.get('err_msg'))
    else:
        return dict_['data']


def similarity(word_pair_list, ip=OFFLINE_IP):
    """
    获取两个词的相似度
    :param word_pair_list:
    :return:
    """
    url = 'http://{}/similarity/'.format(ip)
    data = {
        'words': word_pair_list
    }
    r = requests.post(url, data=json.dumps(data))
    dict_ = json.loads(r.text)
    if dict_.get('err_code') != '00':
        logger.warning("similarity Calc Error, Code:%s, Msg:%s", dict_.get('err_code'), dict_.get('err_msg'))
    else:
        return dict_['data']


def vectors(words, ip=OFFLINE_IP):
    """
    获取词语的词向量
    :param words:
    :return:
    """
    url = 'http://{}/vectors/'.format(ip)
    data = {
        'words': words
    }
    r = requests.post(url, data=json.dumps(data))
    dict_ = json.loads(r.text)
    if dict_.get('err_code') != '00':
        logger.warning("similarity Calc Error, Code:%s, Msg:%s", dict_.get('err_code'), dict_.get('err_msg'))
    else:
        return dict_['data']


def mean_vector(words, ip=OFFLINE_IP):
    """
    获取平均值
    :param words:
    :param ip:
    :return:
    """
    vectors_ = vectors(words)
    if vectors_:
        len_ = len(vectors_[0])
        avg = [0.0] * len_
        c = 0

        for v in vectors_:
            if v:
                for i in range(len_):
                    avg[i] += v[i]
                c += 1
        for i in range(len_):
            avg[i] = avg[i] / c
        return avg

    return None


if __name__ == '__main__':
    import json
    from logger_utility.loggconfig import LoggerConfig, DEBUG
    LoggerConfig().config(True, DEBUG)
    print(json.dumps(similar_top10_words(['你', '开心', '地球']), ensure_ascii=False))
    print(json.dumps(similarity([['你', '开心'],['您', '我'],['月亮', '地球']]), ensure_ascii=False))
    print(json.dumps(mean_vector(['你', '开心', '您', '我', '月亮', '地球']), ensure_ascii=False))


